package com.youth.orderservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.youth.ClientEntity.UserEntity;
import com.youth.commonutils.R;
import com.youth.commonutils.RedisConstants;
import com.youth.orderservice.Client.CourseClient;
import com.youth.orderservice.Client.UserClient;
import com.youth.orderservice.entity.TOrder;
import com.youth.orderservice.entity.TPayLog;
import com.youth.orderservice.mapper.TPayLogMapper;
import com.youth.orderservice.service.TPayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author huangqicai
 * @since 2023-04-29
 */
@Service
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CourseClient courseClient;

    @Autowired
    private UserClient userClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /*根据一些id信息完成支付*/
    @Override
    @Transactional
    public R toPay(TOrder tOrder) {
        /*1.判断该课程该用户原来是否购买过*/
        String courseId = tOrder.getCourseId();
        String memberId = tOrder.getMemberId();
        String redisKey=RedisConstants.COURSE+ courseId;
        Boolean flag = redisTemplate.opsForSet().isMember(redisKey, memberId);
        if(flag){
            return R.error().code(0001).message("当前用户已经购买过该课程,不可重复购买");
        }
        /*2.根据用户id去查询用户余额，判断用户余额是否充足*/
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", memberId);
        UserEntity userEntity = userClient.ByIdGetUser(map);
        String openMoney = userEntity.getOpenMoney();
        BigDecimal openmoney2 = new BigDecimal(openMoney);
        System.out.println("获取到的用户money是:"+openMoney);
        BigDecimal price = tOrder.getPrice();
        if (openmoney2.compareTo(price)<0){
            /*说明余额不足*/
            return R.error().code(0002).message("系统余额不足，请前往充值");
        }
        /*运行到这里，说明符合购买条件*/
        String s = JSON.toJSONString(tOrder);
        rabbitTemplate.convertAndSend("Y", "XB",s);
        /*返回成功的信息，其他处理给消费者进行处理*/
        return R.ok();
    }

}
